use std::{collections::HashMap, hash::Hash};

use super::state::EnumState;

pub struct StateMachine<S, E> {
    current_state: S,
    transitions: HashMap<(S, E), Box<dyn FnMut() -> S>>,
}

impl <S, E> StateMachine<S, E>
where
S: EnumState + Copy + Eq + Hash,
E: PartialEq + Copy + Eq + Hash,
{
    // 实例化状态机
    pub fn new(initial_state: S) -> Self {
        StateMachine { current_state: initial_state, transitions: HashMap::new() }
    }

    // 添加(当前状态, 使用事件, 目标状态处理逻辑)
    pub fn add_transition<F>(&mut self, from_state: S, event: E, to_state_fn: F)
    where 
        F: FnMut() -> S + 'static,
    {
        self.transitions.insert((from_state, event), Box::new(to_state_fn));
    }

    // 触发事件
    pub fn handle_event(&mut self, event: E) {
        if let Some(to_state) = self.transitions.get_mut(&(self.current_state,event)) {
            self.current_state = to_state();
        } else {
            println!("Invalid transition");
        }
    }

    // 获取当前状态
    pub fn get_current_state(&self) -> &S {
        &self.current_state
    }
}